/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import dbs.Broadcast;
import dbs.Comment;
import dbs.Friend;
import dbs.User;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import org.json.JSONObject;

/**
 *
 */
@Stateless
@LocalBean
public class PostBean{

    @EJB
    private UserFacade userFacade;
    
    @EJB
    private BroadcastFacade broadcastFacade;
    
    @EJB
    private CommentFacade commentFacade;
    
    @EJB
    private FriendFacade friendFacade;
    
    @EJB
    private PushMessageBean pushMessageBean;
    
    /**
     * post comment in a channel
     * 
     * @param channelID
     * @param writerID
     * @param content
     * @return 
     */
    public boolean postComment(long channelID, long writerID, String content)
    {
        // check existence of the user
        
        User channelUser = userFacade.findUser(channelID);
        User writerUser = userFacade.findUser(writerID);
        
        if(channelUser == null)
        {
            return false;
        }
        if(writerUser == null)
        {
            return false;
        }
        
        Friend friendData = friendFacade.findFriendData(writerID, channelID);
        if(friendData != null && friendData.getFollowingFlag() == 0)
        {
            // not following
            System.out.println("not follow");
            return false;
        }
        
        Comment newComment = new Comment();
        newComment.setChannelID(channelID);
        newComment.setWriterID(writerID);
        newComment.setDate(new Date());
        newComment.setContent(content);
        
        commentFacade.create(newComment);      
        
        // push gcm
        List<Friend> friendList = friendFacade.findFollowerFriendList(channelID);
        
        List<String> gcmKeyList = new ArrayList<String>();
        
        gcmKeyList.add(channelUser.getGCMkey());
        
        for(Friend friend : friendList)
        {
            User user = userFacade.findUser(friend.getFriendPK().getFriendId());
            
            if(user != null)
            {
                String key = user.getGCMkey();

                System.out.println("MY LOG : gcm KEY - " + key);

                gcmKeyList.add(key);
            }
        }
        
        JSONObject msgJSON = new JSONObject();
        
        msgJSON.put("channelID", channelID);
        try {
            msgJSON.put("writerID", writerID);
            msgJSON.put("writerName", URLEncoder.encode(writerUser.getName(), "UTF-8"));
            msgJSON.put("content", URLEncoder.encode(content, "UTF-8"));
            
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(PostBean.class.getName()).log(Level.SEVERE, null, ex);
            msgJSON.put("writerID", writerID);
            msgJSON.put("writerName", writerUser.getName());
            msgJSON.put("content", content);
        }
        
        try {
            pushMessageBean.pushMessage(gcmKeyList, "newcomment", msgJSON.toString());
        } catch (IOException ex) {
            Logger.getLogger(PostBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return true;
    }
    
    /**
     * broadcast a message in channel.
     * 
     * @param channelID
     * @param content
     * @return 
     */
    public boolean broadcastMessage(long channelID, String content)
    {
        User channelUser = userFacade.findUser(channelID);
        
        if(channelUser == null)
        {
            return false;
        }
        
        Broadcast broadcast =  new Broadcast();
        broadcast.setChannelID(channelID);
        broadcast.setContent(content);
        broadcast.setDate(new Date());
        
        broadcastFacade.create(broadcast);
        
        // push gcm
        List<Friend> friendList = friendFacade.findFollowerFriendList(channelID);
        
        List<String> gcmKeyList = new ArrayList<String>();
        
        gcmKeyList.add(channelUser.getGCMkey());
        
        for(Friend friend : friendList)
        {
            User user = userFacade.findUser(friend.getFriendPK().getFriendId());
            
            if(user != null)
            {
                String key = user.getGCMkey();

                System.out.println("MY LOG : gcm KEY - " + key);

                gcmKeyList.add(key);
            }
        }
        
        JSONObject msgJSON = new JSONObject();
        
        msgJSON.put("channelID", channelID);
        try {
            msgJSON.put("senderName", URLEncoder.encode(channelUser.getName(), "UTF-8"));
            msgJSON.put("content", URLEncoder.encode(content, "UTF-8"));
            
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(PostBean.class.getName()).log(Level.SEVERE, null, ex);
            msgJSON.put("senderName", channelUser.getName());
            msgJSON.put("content", content);
        }
        
        try {
            pushMessageBean.pushMessage(gcmKeyList, "broadcast", msgJSON.toString());
        } catch (IOException ex) {
            Logger.getLogger(PostBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return true;
    }
}
